package com.kai.demo;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

/**
 * Created by wukai on 16/1/4.
 */
public abstract class AbstractButton implements ActionListener {
    protected JTextField textFieldFirst;
    protected JTextField textFieldSecond;
    protected JButton button;

    public Component createComponents() {
        getButton().setMnemonic(KeyEvent.VK_I);
        getButton().setBounds(5, 5, 5, 5);
        getButton().addActionListener(this);

        /*
         * An easy way to put space between a top-level container
         * and its contents is to put the contents in a JPanel
         * that has an "empty" border.
         */
        JPanel pane = new JPanel(new GridLayout(2, 2));
        pane.add(getTextFieldFirst());
        pane.add(getTextFieldSecond());
        pane.add(getButton());
//        pane.add(label);
        pane.setBorder(BorderFactory.createEmptyBorder(
                5, //top
                5, //left
                5, //bottom
                5) //right
        );

        return pane;
    }

    public void actionPerformed(ActionEvent e) {
//        InputStream pypath = this.getClass().getClassLoader().getResourceAsStream("mouse-click.py");
        String pypath = "E:/mouse-click.py";
        System.out.println("pypath = " + pypath);
        String point1 = this.getTextFieldFirst().getText().trim();
        System.out.println("point1 = " + point1);
        exec(pypath, point1);
        String point2 = this.getTextFieldSecond().getText().trim();
        System.out.println("point2 = " + point2);
        exec(pypath, point2);

    }

    private void exec(String pypath, String pointStr) {
        if (pointStr != null && pointStr.length() > 0) {
            String[] location1 = pointStr.split(" ");
            System.out.println("location1 = " + location1.toString());
//            System.out.println("pointStr = " + pointStr);
            if (location1.length > 1) {
                try {
                    String command = "python " + pypath + " " + location1[0] + " " + location1[1];
                    Runtime.getRuntime().exec(command);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public abstract JButton getButton();

    public abstract JTextField getTextFieldFirst();

    public abstract JTextField getTextFieldSecond();


}
